package com.winfield.photovideo;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;





import com.winfield.utils.MyNetWork;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class RegisterActivity extends Activity {

	private EditText user;
	private EditText password;
	private EditText password2;
	
	private static final int REGISTER_SUCCESS_FLAG = 1;   //注册成功 标志1
	private static final int REGISTER_NET_ERROR_FLAG = 2; //因为网络原因  标志2
	private static final int REGISTER_PSW_ERROR_FLAG = 3; //注册过程中两次密码不一致  标志3 
	
	
	//主要是记录用户会话过程中的一些用户的基本信息
	private HashMap<String, String> session =new HashMap<String, String>();
	
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.registeractivity);
        
        user=(EditText)findViewById(R.id.user);
        password=(EditText)findViewById(R.id.password);
        password2=(EditText)findViewById(R.id.password2);

        
    }
    
    
    /**
     * 按下确认按钮的时候  响应这个事件
     * @param v
     */
    public void submitinfo(View v){
    	//Toast.makeText(getApplicationContext(), "我是确认", 1).show();
    	
    	int flag = checkUser(); 
		
		if(flag == REGISTER_PSW_ERROR_FLAG){
			//前后两次输入的密码 不匹配
			Toast.makeText(getApplicationContext(), R.string.register_psw_error, 1).show();
		
		}else if(flag == REGISTER_SUCCESS_FLAG){
		
			//注册成功
			Toast.makeText(v.getContext(), R.string.register_success, Toast.LENGTH_SHORT).show();
			
			Context context = v.getContext();
			Intent intent = new Intent(context,
					MainActivity.class);
			//传递session参数,在用户登录成功后为session初始化赋值,即传递HashMap的值
			Bundle map = new Bundle();				
			map.putSerializable("sessionid", session);
			intent.putExtra("session", map);
			context.startActivity(intent); // 跳转到成功页面	
			
		}
		else{
			//网络原因  注册不成功
			Toast.makeText(v.getContext(), R.string.register_net_error, 1).show();
		}
    	
    }
    
    /**
     * 当按下取消按钮的时候  响应这个事件
     * @param v
     */
    public void cancel(View v){
    	//Toast.makeText(getApplicationContext(), "我是取消", 1).show();
    	System.exit(0);	
    }
    
    
    
    
	/**winfield
	 * 判断输入的信息是否正确
	 * 
	 * 注册成功  返回 1
	 * 网络错误  返回 2
	 * 两次密码不匹配  返回3
	 * 
	 * 
	 * 此处有3个地方  返回了REGISTER_NET_ERROR_FLAG  后期需要斟酌具体原因
	 * 以下功能还没实现
	 * 用户名已经存在 返回4
	 * @return
	 */
    private int checkUser(){
    	
    	String username=user.getText().toString();
    	String pass=password.getText().toString();
    	String pass2=password2.getText().toString();
    	
    	if(!pass.equals(pass2)){
    		//密码不匹配
    		return REGISTER_PSW_ERROR_FLAG;
    	}else
    	{

	    	DefaultHttpClient mHttpClient = new DefaultHttpClient();
			//HttpPost mPost = new HttpPost("http://172.16.44.204/web/php/login.php");
	    	HttpPost mPost = new HttpPost(MyNetWork.PVAPPWEB_P+"regist.php");
	    	
			List<BasicNameValuePair> pairs = new ArrayList<BasicNameValuePair>();
			pairs.add(new BasicNameValuePair("username", username));
			pairs.add(new BasicNameValuePair("password", pass));
			pairs.add(new BasicNameValuePair("password2", pass2));
	
			try {
				mPost.setEntity(new UrlEncodedFormEntity(pairs, HTTP.UTF_8));
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    			
			try {
				HttpResponse response = mHttpClient.execute(mPost);
				int res = response.getStatusLine().getStatusCode();
				
				if (res == 200) {
					HttpEntity entity = response.getEntity();
							
					if (entity != null) {
						String info = EntityUtils.toString(entity);
						System.out.println("info-----------"+info);
						//以下主要是对服务器端返回的数据进行解析
						
						JSONObject jsonObject=null;
						//flag为登录成功与否的标记,从服务器端返回的数据
						String flag="";					
						String name="";
						String userid="";
						String sessionid="";
						try {
							jsonObject = new JSONObject(info);
							flag = jsonObject.getString("flag");
							name = jsonObject.getString("name");
							userid = jsonObject.getString("userid");
							sessionid = jsonObject.getString("sessionid");				
						
						} catch (JSONException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
						//根据服务器端返回的标记,判断服务端端验证是否成功						
						
						if(flag.equals("success")){
							//为session传递相应的值,用于在session过程中记录相关用户信息
							session.put("s_userid", userid);
							session.put("s_username", name);						
							session.put("s_sessionid", sessionid);
							return REGISTER_SUCCESS_FLAG;
						}
						else{
							return REGISTER_NET_ERROR_FLAG;
						}
					}
					else{
						
						return REGISTER_NET_ERROR_FLAG;
					}
						
				}
				
			} catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
	    	
	    	return REGISTER_NET_ERROR_FLAG;
	    }
	
    }
    
    
}